//
//  AddTimeViewController.m
//  jiyujiaProgram
//
//  Created by Jame on 15/10/27.
//  Copyright © 2015年 中良 赵. All rights reserved.
//

#import "AddTimeViewController.h"
#import "AddTimeCell.h"

@interface AddTimeViewController () <CDPDatePickerDelegate,UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>

@end

@implementation AddTimeViewController
{
    UIView *firstView;
    UILabel *_startLabel;
    UILabel *_endLabel;
    CDPDatePicker *_datePicker;
    UITableView *_tableView;
    NSMutableArray *_dataArray;
    BOOL _isStart;
    NSInteger i;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self creatNavigationBarWithImage:nil title:@"上课时间"];
    [self creatNavigationBarLeftItemWithLeftTitle:nil LeftImage:ECIMAGENAME(@"back_button.png")];
    [self creatNavigationBarRightItemWithRightTitle:@"添加" RightImage:nil];
    
    [self creatFirstView];
    [self creatTableView];
    [self creatSubmitButton];
    [self creatDatePicker];

}

- (void)leftBtnClick:(id)leftSender
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)rightBtnClick:(id)rightSender
{
//    [self.navigationController popViewControllerAnimated:YES];
//    if (self.addTime) {
//        self.addTime(_startLabel.text);
//    }
    if (_startLabel.text.length == 5 && _endLabel.text.length == 5) {
        SHOW_ALERT(@"提示", @"请选择时间", @"好的", nil, nil);
    }else{
        if (_isStart) {
            SHOW_ALERT(@"提示", @"请选择结束时间", @"好的", nil, nil);
        }else{
            [_dataArray addObject:_startLabel.text];

            _startLabel.text = @"请选择时间";
            _endLabel.text = @"请选择时间";
            _startLabel.textColor = [UIColor lightGrayColor];
            _endLabel.textColor = [UIColor lightGrayColor];

            [_tableView reloadData];
        }
    }
}


- (void)viewWillAppear:(BOOL)animated
{
    if (_dataArray) {
        [_dataArray removeAllObjects];
    }else{
        _dataArray = [[NSMutableArray alloc] init];
    }
}

- (void)creatFirstView
{
    firstView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, ECSCREEN_W, 88)];
    firstView.backgroundColor = ECCOLOR(255, 255, 255, 1);
    [self.view addSubview:firstView];
    
    //startView
    UIView *startView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ECSCREEN_W, 44)];
    startView.userInteractionEnabled = YES;
    [firstView addSubview:startView];
    
    UILabel *startTitle = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 80, 43)];
    startTitle.text = @"开始日期";
    startTitle.font = [UIFont systemFontOfSize:12.f];
    [startView addSubview:startTitle];
    
    _startLabel = [[UILabel alloc] initWithFrame:CGRectMake(90, 0, ECSCREEN_W - 70 - 20, 43)];
    _startLabel.text = @"请选择时间";
    _startLabel.textColor = [UIColor lightGrayColor];
    _startLabel.font = [UIFont systemFontOfSize:12.f];
    [startView addSubview:_startLabel];
    
    UIButton *startButton = [UIButton buttonWithType:UIButtonTypeCustom];
    startButton.tag = 300;
    [startButton addTarget:self action:@selector(dateClick:) forControlEvents:UIControlEventTouchUpInside];
    startButton.frame = CGRectMake(90, 0, ECSCREEN_W - 70 -20, 43);
    [startView addSubview:startButton];
    
    
    UIImageView *startImage = [[UIImageView alloc] initWithFrame:CGRectMake(ECSCREEN_W - 40, 12, 20, 20)];
    startImage.image = ECIMAGENAME(@"start.png");
    startImage.clipsToBounds = YES;
    startImage.layer.cornerRadius = 10;
    [startView addSubview:startImage];
    
    UIView *startSperaLine = [[UIView alloc] initWithFrame:CGRectMake(0, 43, ECSCREEN_W, 1)];
    startSperaLine.backgroundColor = ECCOLOR(0, 0, 0, .3);
    [startView addSubview:startSperaLine];
    
    
    //endView
    UIView *endView = [[UIView alloc] initWithFrame:CGRectMake(0, 44, ECSCREEN_W, 44)];
    endView.userInteractionEnabled = YES;
    [firstView addSubview:endView];
    
    UILabel *endTitle = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 80, 43)];
    endTitle.text = @"结束日期";
    endTitle.font = [UIFont systemFontOfSize:12.f];
    [endView addSubview:endTitle];
    
    _endLabel = [[UILabel alloc] initWithFrame:CGRectMake(90, 0, ECSCREEN_W - 70 - 20, 43)];
    _endLabel.text = @"请选择时间";
    _endLabel.textColor = [UIColor lightGrayColor];
    _endLabel.font = [UIFont systemFontOfSize:12.f];
    [endView addSubview:_endLabel];
    
    
    UIButton *endButton = [UIButton buttonWithType:UIButtonTypeCustom];
    endButton.tag = 301;
    [endButton addTarget:self action:@selector(dateClick:) forControlEvents:UIControlEventTouchUpInside];
    endButton.frame = CGRectMake(90, 0, ECSCREEN_W - 70 -20, 43);
    [endView addSubview:endButton];
    
    
    UIImageView *endImage = [[UIImageView alloc] initWithFrame:CGRectMake(ECSCREEN_W - 40, 12, 20, 20)];
    endImage.image = ECIMAGENAME(@"stop.png");
    endImage.clipsToBounds = YES;
    endImage.layer.cornerRadius = 10;
    [endView addSubview:endImage];
    
    UIView *endSperaLine = [[UIView alloc] initWithFrame:CGRectMake(0, 43, ECSCREEN_W, 1)];
    endSperaLine.backgroundColor = ECCOLOR(0, 0, 0, .3);
    [endView addSubview:endSperaLine];
}


- (void)creatDatePicker
{
    _datePicker=[[CDPDatePicker alloc] initWithView:self.view delegate:self];
}


#pragma mark - CDPDatePickerDidConfirm
//回调，字符串可自行进行截取
-(void)CDPDatePickerDidConfirm:(NSString *)confirmString{
    if (_isStart) {
        _startLabel.textColor = [UIColor blackColor];
        _startLabel.text = confirmString;
        if (_endLabel.text.length > 0) {
            NSDate *endDate = [NSDate dateFromString:_endLabel.text withFormat:@"yyyy-MM-dd HH:mm"];
            NSDate *startDate = [NSDate dateFromString:_startLabel.text withFormat:@"yyyy-MM-dd HH:mm"];
            if ([startDate timeIntervalSinceDate:endDate] > 0) {
                _endLabel.text = @"请选择时间";
                _endLabel.textColor = [UIColor lightGrayColor];
            }
        }
        
    }else{
        _endLabel.textColor = [UIColor blackColor];
        _endLabel.text = confirmString;
    }
}


- (void)dateClick:(UIButton *)button
{
    if (button.tag == 300) {
        _isStart = YES;
        [_datePicker setIsBeforeTime:YES WithData:[NSDate date]];
        [_datePicker pushDatePicker];
    }else{
        if ([_startLabel.text isEqualToString:@"请选择时间"]) {
//            _alertView = [[SCLAlertView alloc] init];
//            [_alertView showWarning:self title:@"Warning" subTitle:@"请先选择开始时间" closeButtonTitle:@"好的" duration:.0f];
            SHOW_ALERT(@"提示", @"请先选择开始时间", @"好的", nil, nil);
        }else{
            NSDate *date = [NSDate dateFromString:_startLabel.text withFormat:@"yyyy-MM-dd HH:mm"];
            NSLog(@"******DATE******%@******LABEL******%@",date,_startLabel.text);
            [_datePicker setIsBeforeTime:NO WithData:[NSDate dateWithTimeInterval:60*60 sinceDate:date]];
            _isStart = NO;
            [_datePicker pushDatePicker];
        }
    }
}




- (void)creatTableView
{
    self.automaticallyAdjustsScrollViewInsets = YES;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 152 + 5, ECSCREEN_W, ECSCREEN_H - 152 - 5 - 55) style:UITableViewStylePlain];
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    _tableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_tableView];
    
    _tableView.tableFooterView = [[UIView alloc]init];
    
    if ([_tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [_tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([_tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [_tableView setLayoutMargins:UIEdgeInsetsZero];
    }
}


#pragma mark - tableViewNumberOfRowsInSection
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArray.count;
}


#pragma mark - tableViewHeightForRowAtIndexPath
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44.f;
}


#pragma mark - tableViewCellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *reuseIdentifier = @"addTimeCell";
    AddTimeCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (nil == cell) {
        NSArray *arr = [[NSBundle mainBundle]loadNibNamed:@"AddTimeCell" owner:nil options:nil];
        for (NSObject *obj in arr) {
            if ([obj isKindOfClass:[AddTimeCell class]]) {
                cell = (AddTimeCell *)obj;
                if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
                    [cell setSeparatorInset:UIEdgeInsetsZero];
                }
                if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
                    [cell setLayoutMargins:UIEdgeInsetsZero];
                }
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                break;
            }
        }
    }
    [cell setCellWithModel:_dataArray WithIndexPath:indexPath];
    return cell;
}



- (void)creatSubmitButton
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.tag = 118;
    button.frame = CGRectMake(10, ECSCREEN_H - 50, ECSCREEN_W - 20, 40);
    button.clipsToBounds = YES;
    button.layer.cornerRadius = 5;
    button.backgroundColor = NAVC_COLOR;
    [button setTitle:@"提交课程" forState:UIControlStateNormal];
    [button setTitleColor:ECCOLOR(255, 255, 255, 1) forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:13.f];
    [button addTarget:self action:@selector(submitClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}



- (void)submitClick:(UIButton *)button
{
    i = 0;
    for (NSString *date in _dataArray) {
        NSString *time = [date stringByReplacingOccurrencesOfString:@" " withString:@"T"];
        time = [NSString stringWithFormat:@"%@:00",time];
        NSLog(@"%@",time);
        
        NSDictionary *dict =@{
                              @"promulgator_Id":self.data[@"promulgator_Id"],
                              @"t_member_Id":self.data[@"t_member_Id"],
                              @"promulgator_mark":@"1",
                              @"course_name":self.data[@"course_name"],
                              @"price":self.data[@"price"],
                              @"suits_the_crowd":self.data[@"suits_the_crowd"],
                              @"course_content":self.data[@"course_content"],
                              @"class_time":time,
                              @"have_class_way":self.data[@"have_class_way"],
                              @"lng":self.data[@"lng"],
                              @"lat":self.data[@"lat"],
                              @"status":@"1",
                              @"course_ImgIds":self.data[@"course_ImgIds"],
                              @"course_video_Ids":self.data[@"course_video_Ids"],
                              };
        NSLog(@"********DICT%@*********",dict);

        [self creatHttpRequestWithDict:dict];
    }
}


- (void)creatHttpRequestWithDict:(NSDictionary *)data
{
    NSDictionary *param = @{
                            @"data":data,
                            };
    
    [[HttpManager defaultManager] postRequestToUrl:RequestURL(UPDATECOURSE) params:param complete:^(BOOL successed, NSDictionary *result) {
        if (successed) {
            i++;
            if ([result[@"errCode"] integerValue] == 200) {
                if (i == _dataArray.count) {
                    SHOW_ALERT(@"提示", result[@"errMsg"], @"好的", nil, self);
                }
            }else{
                SHOW_ALERT(@"提示", result[@"errMsg"], @"好的", nil, nil);
            }
        }
    }];
}



- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
